package com.jfinal.ext.plugin.mail;

import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.IPlugin;
import org.jetbrains.annotations.NotNull;

import java.util.Properties;

/**
 * @author Timor
 * @version 1.0
 * @date 2022/10/14 17:53:33
 */
public class MailPlugin implements IPlugin {
    public static final String MAIN_CONFIG = "main";
    private final String configName;
    private final Properties props;
    private String protocol;


    public MailPlugin(@NotNull final Properties props) {
        this(MAIN_CONFIG, props);
    }

    public MailPlugin(@NotNull final String configName,
                      @NotNull final Properties props) {
        this.configName = configName;
        this.props = props;
    }


    @Override
    public boolean start() {
        protocol = props.getProperty("mail.transport.protocol");

        if (StrKit.isBlank(protocol)) {
            throw new RuntimeException("未设置: mail.transport.protocol");
        }


        check("host");
        check("auth", "true");
        check("timeout", "10000");

        // 使用ssl协议时，需要配置端口
        if (checkValue("ssl.enable", "true")) {
            check("port");
        }

        final String username = props.getProperty("username");
        final String password = props.getProperty("password");

        if (StrKit.isBlank(username)) {
            throw new RuntimeException("未设置用户名");
        }

        if (StrKit.isBlank(password)) {
            throw new RuntimeException("未设置密码");
        }

        MailKit.add(configName, new MailServiceImpl(props, username, password));
        return true;
    }


    void check(@NotNull final String attr) {
        final String key = "mail." + protocol + "." + attr;

        if (StrKit.isBlank(props.getProperty(key))) {
            throw new RuntimeException("未设置: " + key);
        }
    }

    void check(@NotNull final String attr, @NotNull final String defaultValue) {
        final String key = "mail." + protocol + "." + attr;

        if (StrKit.isBlank(props.getProperty(key))) {
            props.setProperty(key, defaultValue);
            LogKit.warn("未设置: " + key + "，使用默认值: " + defaultValue);
        }
    }

    boolean checkValue(@NotNull final String attr, @NotNull final String value) {
        final String key = "mail." + protocol + "." + attr;

        return value.equals(props.getProperty(key));
    }


    @Override
    public boolean stop() {
        return true;
    }
}
